package com.hy.utils.filter;

import cn.hutool.core.util.StrUtil;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(value = "/back/*", filterName ="backLoginFilter" )
public class BackLoginFilter implements Filter {
    //不需要登录验证的url
    private static List<String> noLoginValidateUrlList;

    //不需要权限验证的url
    private static List<String> noPriValidateUrlList;

    //跳转到的登录页面
    private static String LOGIN_URL;

    //没有权限的界面
    private static String NO_PRIVILEGE_URL;

    static{
        noLoginValidateUrlList=new ArrayList<String>();
        //静态资源
        //noLoginValidateUrlList.add("/static/");
        //登录页面
        //http://localhost:8080/demo042/back/admin?ac=tologin
        noLoginValidateUrlList.add("/login/admin.jsp");
        //登录方法
        noLoginValidateUrlList.add("/back/admin?ac=selectLogin");
        //退出方法
//        noLoginValidateUrlList.add("/back/admin?ac=selectLogin");


//        noPriValidateUrl=new ArrayList<String>();
//        noPriValidateUrl.add("/Main?jsp=toMain");
//        //查询权限
//        noPriValidateUrl.add("/Privilege?method=getPrivilegeByUId");
//        //退出
//        noPriValidateUrl.add("/User?method=logout");
//
//        LOGIN_URL="/WEB-INF/admin/login.jsp";
//        NO_PRIVILEGE_URL="/WEB-INF/pages/noPrivilege.jsp";
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        String requestURI = request.getRequestURI();  // /demo042/back/admin

        String newRequestURI = requestURI.substring(request.getContextPath().length());
        String ac = request.getParameter("ac");

        if(StrUtil.isBlank(ac))
            return;

        String path = newRequestURI+"?ac="+ac;

        for(String noLoginValidateUrl :noLoginValidateUrlList){
            if(noLoginValidateUrl.equals(path)){
                chain.doFilter(request,response);
                return;
            }
        }

        //进行登录验证

        HttpSession session = request.getSession(true);

        Object admin = session.getAttribute("admin");

        if(admin == null){ //没有登录
            response.sendRedirect(request.getContextPath()+"/login/admin.jsp");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
